/*
 * Copyright (c) 2018, Nordic Semiconductor
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.aispeech.rcprvd.profile;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.util.Log;

import java.util.Arrays;
import java.util.UUID;

import androidx.annotation.NonNull;
import no.nordicsemi.android.ble.callback.DataReceivedCallback;
import no.nordicsemi.android.ble.data.Data;
import no.nordicsemi.android.ble.livedata.ObservableBleManager;

public class JinjuBleManager extends ObservableBleManager {
    public final static String TAG = "JinjuBleManager";

    //设备信息服务
    private static final UUID BLE_INFO_SERVICE_UUID = UUID.fromString("0000180a-0000-1000-8000-00805f9b34fb");
    //设备电池服务
    private static final UUID BLE_BATTERY_SERVICE_UUID = UUID.fromString("0000180f-0000-1000-8000-00805f9b34fb");

    //语音服务uuid
    public final static UUID LBS_UUID_SERVICE = UUID.fromString("a8253f01-0c51-4000-b84f-1500068fb5a3");
    //Voice key event characteristic UUID.
    private final static UUID LBS_UUID_KEY_CHAR = UUID.fromString("a8253f02-0c51-4000-b84f-1500068fb5a3");
   //Voice data characteristic UUID.
    private final static UUID LBS_UUID_DATA_CHAR = UUID.fromString("a8253f03-0c51-4000-b84f-1500068fb5a3");

    private BluetoothGattCharacteristic mVoiceKeyCharacteristic, mVoiceDataCharacteristic;
    private boolean supported;

    private  DataReceivedCallback mVoiceDataCallback;
    private DataReceivedCallback mVoiceKeyEventCallback;

    public JinjuBleManager(@NonNull final Context context, DataReceivedCallback voiceKeyEventCallback, DataReceivedCallback voiceDataCallback) {
        super(context);
        mVoiceKeyEventCallback = voiceKeyEventCallback;
        mVoiceDataCallback = voiceDataCallback;
    }

    @NonNull
    @Override
    protected BleManagerGattCallback getGattCallback() {
        return new JinjuBleManagerGattCallback();
    }

//    /**
//     * Sets the log session to be used for low level logging.
//     *
//     * @param session the session, or null, if nRF Logger is not installed.
//     */
//    public void setLogger(@Nullable final LogSession session) {
//        logSession = session;
//    }

    @Override
    public void log(final int priority, @NonNull final String message) {
        // The priority is a Log.X constant, while the Logger accepts it's log levels.
//        Logger.log(logSession, LogContract.Log.Level.fromPriority(priority), message);
    }

    @Override
    protected boolean shouldClearCacheWhenDisconnected() {
        return !supported;
    }

    /**
     * BluetoothGatt callbacks object.
     */
    private class JinjuBleManagerGattCallback extends BleManagerGattCallback {
        @Override
        protected void initialize() {
            setNotificationCallback(mVoiceKeyCharacteristic).with(mVoiceKeyEventCallback);
            setNotificationCallback(mVoiceDataCharacteristic).with(mVoiceDataCallback);

//            readCharacteristic(mVoiceDataCharacteristic).with(ledCallback).enqueue();
//            readCharacteristic(mVoiceKeyCharacteristic).with(buttonCallback).enqueue();
            enableNotifications(mVoiceKeyCharacteristic).enqueue();
            enableNotifications(mVoiceDataCharacteristic).enqueue();
        }

        @Override
        public boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) {
            Log.d(TAG, "isRequiredServiceSupported: ");
            final BluetoothGattService service = gatt.getService(LBS_UUID_SERVICE);
            if (service != null) {
				Log.d(TAG, "isRequiredServiceSupported: 1");
				mVoiceKeyCharacteristic = service.getCharacteristic(LBS_UUID_KEY_CHAR);
                mVoiceDataCharacteristic = service.getCharacteristic(LBS_UUID_DATA_CHAR);
            }

            boolean writeRequest = false;
            if (mVoiceDataCharacteristic != null) {
				Log.d(TAG, "isRequiredServiceSupported: 2");
				final int rxProperties = mVoiceDataCharacteristic.getProperties();
//                writeRequest = (rxProperties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0;
                writeRequest = (rxProperties & BluetoothGattCharacteristic.PROPERTY_READ) > 0;
            }

            supported = mVoiceKeyCharacteristic != null && mVoiceDataCharacteristic != null && writeRequest;
			Log.d(TAG, "isRequiredServiceSupported: " + supported);
			return supported;
        }

        @Override
        protected void onDeviceDisconnected() {
            mVoiceKeyCharacteristic = null;
            mVoiceDataCharacteristic = null;
        }
    }
//
//    /**
//     * Sends a request to the device to turn the LED on or off.
//     *
//     * @param on true to turn the LED on, false to turn it off.
//     */
//    public void turnLed(final boolean on) {
//        // Are we connected?
//        if (mVoiceDataCharacteristic == null)
//            return;
//
//        // No need to change?
//        if (ledOn == on)
//            return;
//
//        log(Log.VERBOSE, "Turning LED " + (on ? "ON" : "OFF") + "...");
//        writeCharacteristic(mVoiceDataCharacteristic,
//                on ? BlinkyLED.turnOn() : BlinkyLED.turnOff())
//                .with(ledCallback).enqueue();
//    }
}
